package com.cac.demo.service.directDelivery;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cac.demo.controller.CallInterFace.SendMaterialInterface;
import com.cac.demo.dao.directDelivery.DirectDeliveryDao;
import com.cac.demo.dao.dispatchSearch.MsDeliveryPackageInfoDao;
import com.cac.demo.dao.materialScan.WmsDeliverPlanDao;
import com.cac.demo.entity.materialScan.WmsDeliverPlanDTO;
import com.cac.demo.service.CallInterface.CallInterfaceService;
import com.cac.demo.service.FinProReceive.FinProReceiveSearchService;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.DaoException;
import com.cac.demo.util.adapter.QueryReqBean;
import com.cac.demo.util.adapter.QueryRespBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * @className: DirectDeliveryService
 * @description: （描述这个类的作用）
 * @author: lqc
 * @date: 2023/7/10 15:08:08 周一
 * @version: 1.0
 */
@Service
@Slf4j
public class DirectDeliveryService {

    @Autowired
    private DirectDeliveryDao directDeliveryDao;
    @Autowired
    private FinProReceiveSearchService finProReceiveSearchService;
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    @Autowired
    private MsDeliveryPackageInfoDao msDeliveryPackageInfoDao;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private Environment environment;
    @Autowired
    private WorkService workService;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private SendMaterialInterface sendMaterialInterface;

    //分拣配套页面数据查询
    public QueryRespBean<HashMap> searchByPage(QueryReqBean<HashMap> queryReqBean) {
        QueryRespBean<HashMap> queryRespBean = new QueryRespBean<>();
        try {
            PageHelper.startPage(queryReqBean.getPageParameter());
            HashMap searchParams = queryReqBean.getSearchParams();
            Page<HashMap> dataList = directDeliveryDao.searchMsAoMatchInfoByPage(searchParams);
            queryRespBean.setResult(dataList);
            return queryRespBean;
        } catch (Exception e) {
            throw new DaoException(e.getMessage());
        }
    }

    //直配入库传递参数到ERP
    public void sendParamToErp(HashMap map) {
        HashMap issuedTest = new HashMap();
        HashMap param = new HashMap();
        JSONObject headersMap = new JSONObject();
        try {
            String func = wmsDeliverPlanDao.searchFuncById(map.get("wmsDeliveryPlanId").toString());
            //查询是否发起协调
            HashMap isCo = finProReceiveSearchService.searchCoordinate(map.get("wmsDeliveryPlanId").toString());
            if (func.equals("ERP-101-preConfirmCp")) {
                if (Objects.isNull(isCo)) {
                    headersMap.put("func", "101-ERP-scanRecieveCp");
                    issuedTest.put("type", "101-ERP-scanRecieveCp");
                } else {
                    String WMS_DELIVERY_COORDINATE_ID = (String) isCo.get("WMS_DELIVERY_COORDINATE_ID");
                    headersMap.put("func", "101-ERP-scanZeroRecieveCp");
                    param.put("wmsCoordinateInfoId", WMS_DELIVERY_COORDINATE_ID);
                    //工控网上传数据
                    issuedTest.put("type", "101-ERP-scanZeroRecieveCp");
                }
            } else if (func.equals("ERP-101-preConfirmLj")) {
                if (Objects.isNull(isCo)) {
                    headersMap.put("func", "101-ERP-scanRecieveLj");
                    param.put("sealDate", map.get("sealDate") == null ? " " : map.get("sealDate"));
                    param.put("ensureDate", map.get("ensureDate") == null ? " " : map.get("ensureDate"));
                    param.put("maxStorageDate", map.get("maxStorageDate") == null ? " " : map.get("maxStorageDate"));
                    param.put("recieveNote", map.get("remark") == null ? " " : map.get("remark"));
                    //工控网上传数据
                    issuedTest.put("type", "101-ERP-scanRecieveLj");
                } else {
                    String WMS_DELIVERY_COORDINATE_ID = (String) isCo.get("WMS_DELIVERY_COORDINATE_ID");
                    headersMap.put("func", "101-ERP-scanZeroRecieveLj");
                    param.put("wmsCoordinateInfoId", WMS_DELIVERY_COORDINATE_ID);
                    //工控网上传数据
                    issuedTest.put("type", "101-ERP-scanZeroRecieveLj");
                }
            } else {
                headersMap.put("func", "101-ERP-scanRecieveBzj");
                //工控网上传数据
                issuedTest.put("type", "101-ERP-scanRecieveBzj");
            }
            param.put("wmsPreDeliveryPlanId", map.get("wmsDeliveryPlanId").toString());
            param.put("wmsItemInventoryId", map.get("itemId").toString());
            //查询是无库存交接
            WmsDeliverPlanDTO dto = new WmsDeliverPlanDTO();
            dto.setWmsDeliveryPlanId(map.get("wmsDeliveryPlanId").toString());
            HashMap ret = wmsDeliverPlanDao.searchDeliveryType(dto.getWmsDeliveryPlanId());
            if (!Objects.isNull(ret) && ret.containsKey("attribute5Desc")) {
                if ("NOINV".equals(ret.get("attribute5Desc"))) {
                    param.put("inventoryCode", "101-FJZX");
                }
            }
            param.put("recieveNote", map.get("remark") == null ? " " : map.get("remark"));
            param.put("locatorNo", "101");
            param.put("recieveQty", map.get("deliveryQty"));//此处应该用移交数量
            param.put("opUserCode", map.get("userCode"));
            param.put("userIp", map.get("IP"));
            JSONObject data = new JSONObject(param);
            headersMap.put("data", data);
            String msgId = CreatMsgId.getMsgId();
            headersMap.put("msgId", msgId);
            callInterfaceService.sendBData("sendBData", "两网传输-发送业务数据",
                    CallInterfaceService.encodeBData(JSON.toJSONString(headersMap)), "直配入库");
            issuedTest.put("BData", headersMap.toJSONString());
            issuedTest.put("msgId", msgId);
            workService.issuedTest(issuedTest);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    //接收直配方法上传分拣占用
    public void allBData(HashMap map) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        JSONObject headersMap = new JSONObject();
        String msgId = CreatMsgId.getMsgId();
        HashMap param = new HashMap();
        //获取func
        headersMap.put("func", "101-ERP-sortingAllot");
        headersMap.put("msgId", msgId);
        //查询占用id
        String id = directDeliveryDao.searchAllotId(map);
        //分拣占用接口所需参数
        param.put("opUserCode", map.get("userCode").toString());
        param.put("originalId", id);
        param.put("wmsItemInventoryId", map.get("itemId").toString());
        param.put("productCode", map.get("productCode").toString());
        param.put("batchNo", map.get("batchNo").toString());
        param.put("startLotNo", map.get("startPlaneNo").toString());
        param.put("endLotNo", map.get("startPlaneNo").toString());
        param.put("applyQty", map.get("itemQty").toString());
        param.put("allotmentQty", map.get("itemQty").toString());
        param.put("wmsPreDeliveryPlanId", map.get("wmsDeliveryPlanId"));
        param.put("aoNo", map.get("aoCode").toString());
        param.put("userIp", map.get("IP"));
        param.put("taskNo", "");
        param.put("recHrDeptId", "");
        //装换为json格式
        JSONObject data = new JSONObject(param);
        headersMap.put("data", data);
        String headersmap = headersMap.toJSONString();
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String parameters = encoder.encodeToString(headersmap.getBytes());
        String code = "sendBData";
        String sendScenario = "分拣占用";
        String name = "两网传输-发送业务数据";
        callInterfaceService.sendBData(code, name, parameters, sendScenario);

        //工控网上传数据
        HashMap issuedTest = new HashMap();
        issuedTest.put("BData", headersmap);
        issuedTest.put("msgId", msgId);
        issuedTest.put("type", headersMap.get("func"));
        workService.issuedTest(issuedTest);
    }

    @Async
    public void dispatch(String carCode, List<String> toolCodes, HashMap hashMap) {
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String groupCode = ComUtil.getId();
        HashMap map = new HashMap();
        map.put("carCode", carCode);
        map.put("groupCode", groupCode);
        map.put("outInt", null);
        map.put("outString", null);
        //绑定小车编码和托盘编码，创建交接单，调用分拣出库回传ERP
        for (String toolCode : toolCodes) {
            map.put("toolCode", toolCode);
            msDeliveryPackageInfoDao.callCarCodeBle(map);
            log.info("配送生成交接单信息："+map.toString());
            //修改matchInfo配送状态
            msDeliveryPackageInfoDao.updateMatchInfo(toolCode, hashMap.get("userCode").toString(), hashMap.get("IP").toString());
            msDeliveryPackageInfoDao.updateWorkBin(toolCode);
            //判断当前ao下物料是否全部配送
            HashMap ao = msDeliveryPackageInfoDao.selectAoDeliveryState(toolCode);
            if (!Objects.isNull(ao)) {//不为空，当前ao已经全部配送，修改ao状态为全部配送
                msDeliveryPackageInfoDao.updateTaskAoAll(ao);
                //修改工作包配送状态为全部
                int cnt = msDeliveryPackageInfoDao.updatePackageAll(ao);
                if (cnt == 0) {
                    //修改工作包配送状态为部分
                    msDeliveryPackageInfoDao.updatePackagePart(ao);
                }
            } else {//修改ao状态为部分配送
                msDeliveryPackageInfoDao.updateTaskAoPart(toolCode);
            }
        }
        //更新小车状态
        msDeliveryPackageInfoDao.updateWorkbinCar(carCode);

        //网闸数据打包接口所需参数，以及发送文件所需func
        HashMap paramMap = new HashMap();
        //网闸查询场景编码
        paramMap.put("dmsCode", "ms_gzbps");
        //网闸查询数据SQL所需条件
        paramMap.put("delivery_plan_code", groupCode);
        HashMap interfaceMap = new HashMap();
        interfaceMap.put("code", "getMatchData");
        interfaceMap.put("name", "获取数据配套场景的配套数据");
        interfaceMap.put("parameters", paramMap);
        //发送文件所需func
        interfaceMap.put("func", "101-MES-FenjianMaterialSend");
        interfaceMap.put("sendScenario", "物料配送");
        log.info("=====================" + interfaceMap.toString());
        //文件上传ERP
        sendMaterialInterface.SendFileInterface(interfaceMap);

    }
}
